package com.service.impl;

import com.entity.ComponentCatalog;
import com.exception2.CodeMirrorException;
import com.repository.ComponentCatalogRepository;
import com.request.ComponentCatalogRequest;
import com.response.ComponentCatalogResponse;
import com.service.ComponentCatalogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ComponentCatalogServiceImpl implements ComponentCatalogService {
    @Autowired
    private ComponentCatalogRepository componentCatalogRepository;
    @Override
    public ComponentCatalogResponse save(ComponentCatalogRequest componentCatalogRequest) {

        String handle = componentCatalogRequest.getHandle();
        if(StringUtils.isEmpty(handle)){
            throw new CodeMirrorException("请填写handle");
        }
        ComponentCatalog componentCatalog = null;
        if(componentCatalogRequest.getId() != null ){
            componentCatalog = componentCatalogRepository.getOne(componentCatalogRequest.getId());
        }


        switch (handle){
            case "add":
                this.checkName(componentCatalogRequest.getCatalog());
                componentCatalogRequest.setCrDate(componentCatalogRequest.getDate());
                componentCatalogRequest.setCrUser(componentCatalogRequest.getUserName());
                componentCatalogRequest.setCrId(componentCatalogRequest.getUserId());
                componentCatalog = componentCatalogRepository.save(componentCatalogRequest);
                break;
            case "update":

                this.checkId(componentCatalogRequest.getId());
                this.checkName(componentCatalogRequest.getCatalog());
                componentCatalogRequest.setMoDate(componentCatalogRequest.getDate());
                componentCatalogRequest.setMoUser(componentCatalogRequest.getUserName());
                componentCatalog = componentCatalogRepository.save(componentCatalogRequest);
                break;
            case "query":
                break;
            case "del":
                componentCatalogRepository.deleteById(componentCatalogRequest.getId());
                componentCatalog = null;
        }
        ComponentCatalogResponse componentCatalogResponse = (ComponentCatalogResponse) componentCatalog;
        return componentCatalogResponse;
    }
    private void checkId(Integer id){
        if(id == null || id  == 0){
            throw new CodeMirrorException("请填写id");
        }
    }

    private void checkName(String name){
        ComponentCatalog componentCatalog = componentCatalogRepository.findByCatalog(name);
        if(componentCatalog != null ){
            throw new CodeMirrorException(String.format("%s已存在",componentCatalog.getCatalog()));
        }
    }
}
